package com.corner.presenter.imp;

import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.UserHelper;
import com.corner.presenter.IUserSettingPresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.IUserSettingView;
import com.corner.utils.BitmapUtil;

import java.io.IOException;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/7/15，23.22.
 * 描述：
 */
public class UserSettingPresenter extends BasePresenter<IUserSettingView> implements IUserSettingPresenter {
    @Override
    public void requestUser() {
        UserHelper.getUser(User.getCurrentUser().getObjectId()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<User>() {
            @Override
            public void call(User user) {
                if (user != null) {
                    if (view != null) view.requestUserSucess(user);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });
    }


    @Override
    public void changeAvater(final float[] scales, final String currentPicPath) {

        view.showLoading(true);
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    BitmapUtil.cutBitmap(currentPicPath, currentPicPath, scales);
                    BitmapUtil.compressBitmap(currentPicPath,currentPicPath);
                    subscriber.onNext(currentPicPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(new Throwable("我也不知道为什么，不能处理你的照片，请重新试一次吧"));
                }
            }
        }).flatMap(new Func1<String, Observable<User>>() {
            @Override
            public Observable<User> call(String s) {
                return UserHelper.changeAvater(User.getCurrentUser(), currentPicPath);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<User>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (view != null) {
                    view.changeAvaterError(e.getMessage());
                    view.showLoading(false);
                }
            }

            @Override
            public void onNext(User user) {
                if (view != null) {
                    view.changeAvaterSucess();
                    User.cacheUser(user);
                    UserHelper.saveUserToDb(user);
                    view.showLoading(false);
                }
            }
        });
    }
}
